<template>
    <div class="step">
        <div class="con_title">
            <div>
                <span class="main_title">推送周期及内容</span>
            </div>
            <template v-if="!props.look">
                <el-button v-if="rules.length !== 0" type="primary" @click="openCofig">添加规则</el-button>
            </template>
        </div>
        <div v-if="rules.length == 0" class="emty_content">
            <img class="emty_img" src="@/assets/noData.png" alt="" />
            <div class="emty_title">您还没有添加任何SOP规则</div>
            <el-button style="margin-top: 20px" type="primary" @click="openCofig">添加规则</el-button>
        </div>
        <div v-else class="main_rule">
            <div v-for="(item, index) in rules" :key="index" class="rule_item">
                <div class="rule_item_title">
                    <div class="index_num">{{ index + 1 }}</div>
                    <div v-if="item.trigger_time_type == 1" class="title_icon">单</div>
                    <div v-else class="title_icon week_icon">周</div>
                    <span v-if="item.trigger_time_type == 1">
                        {{
                            `${phase()}${
                                item.trigger_time_type == 1
                                    ? item.execute_time_local == 1
                                        ? `${[4, 5].includes(props.formData.trigger_range.sop_scene) ? '后，' : '时，'}`
                                        : '前，'
                                    : '后'
                            }`
                        }}
                        <span v-if="Number(item.execute_time) != 0">
                            {{ item.execute_time }}
                            {{ getDayStr(item.execute_time_type) }}
                            {{ isShowDom(item) }}
                            {{ item.execute_time == 0 ? null : item.execute_time_type == 'day' ? '的' : null }}
                            {{ item.execute_time_type == 'day' ? item.execute_time_hour : null }}
                        </span>
                        <span v-else>
                            {{ item.execute_time_type == 'day' ? '当天' + item.execute_time_hour : '立即' }}
                        </span>
                        <span>{{ getSendType(item.trigger_type) }}</span>
                    </span>
                    <span v-else>
                        {{ `${phase()}${[4, 5].includes(props.formData.trigger_range.sop_scene) ? '后' : '时'}，` }}
                        <span>
                            每{{ item.execute_time == 0 ? null : item.execute_time }}
                            {{ getDayStr(item.execute_time_type) }}
                            {{ item.execute_time == 0 ? null : item.execute_time_type == 'day' ? '的' : null }}
                            {{ item.execute_time_type == 'day' ? item.execute_time_hour : null }}
                        </span>
                        <span>{{ getSendType(item.trigger_type) }}</span>
                    </span>
                </div>
                <div class="rule_box">
                    <div class="rule_tit">
                        <span>【内容标题：{{ item.title }}】</span>
                        <div v-if="!props.look" style="font-size: 14px; color: #969696; cursor: pointer">
                            <el-tooltip effect="light" content="编辑" placement="top">
                                <edit
                                    style="width: 1em; height: 1em; margin-right: 30px"
                                    @click="openCofig(item, index, 'edit')" />
                            </el-tooltip>
                            <el-tooltip effect="light" content="复制" placement="top">
                                <copy-document
                                    style="width: 1em; height: 1em; margin-right: 30px"
                                    @click="openCofig(item, index, 'copy')" />
                            </el-tooltip>
                            <el-tooltip effect="light" content="删除" placement="top">
                                <delete style="width: 1em; height: 1em" @click="removeConfig(item, index)" />
                            </el-tooltip>
                        </div>
                    </div>
                    <div class="rule_content">{{ item.welcome_info.welcome_text }}</div>
                    <ul class="rule_file">
                        <li v-for="v in item.fileList" :key="v.name" class="file_item">
                            <div>
                                <img class="file_icon" :src="v.icon" alt="" />
                                <span>{{ sortName(v.name) }}</span>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <!--选择成员 -->
        <SopConfig
            ref="SopConfigRef"
            from="1"
            :rule-index="ruleIndex"
            :config-str="configStr"
            :scene="phase"
            :type="props.formData.trigger_range.trigger_condition.type"
            :birth="props.formData.trigger_range.sop_scene"
            @getFileList="getFileList"
            @submit="getSop" />
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="ZWDeletdialogRef" @submit="confirmDel" />
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import SopConfig from '../../../components/sopConfig.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { getSuffixIcon, IsNotEmpty, deepClone, initMaterialData } from '@/utils/utils';
import { stageList } from '@/api/customerCenter/labellagroup';
import { festivalDay } from '@/api/smartMarketing/sop';

const props = defineProps(['formData', 'look', 'pageType']);
const creators = ref([]);
const route = useRoute();
const SopConfigRef = ref(null);
const ZWDeletdialogRef = ref(null);
const configStr = ref('');
const sceneType = ref(route.query.scene);
const configIndex = ref(0);
const state_list = ref([]);
const holiday_list = ref([]);

const materialContentDataList = ref<Array<any>>([]);
const materialContentFormList = ref<Array<any>>([]);
const ruleIndex = ref<number>(0);

const rules = computed(() => {
    return props.formData.rule;
});

const isShowDom = computed(() => {
    return item => {
        if (
            item.execute_time_local == 1 &&
            item.trigger_time_type == 1 &&
            ![4, 5].includes(props.formData.trigger_range.sop_scene)
        ) {
            return '后';
        } else {
            return '';
        }
    };
});
// eslint-disable-next-line vue/no-dupe-keys
const formData = ref({
    execute_time2: '8',
    execute_time_type2: 'day',
    execute_time_hour1: '08:00',
    trigger_type: '1', //1 员工任务 2 企业微信纯提醒 3 公众号消息 4 短信
    trigger_time_type: '1', //1 定时推送 2 周期推送
    execute_time: '8', //执行周期
    execute_time_type: 'day', //时间类型minute 分钟 hour 小时 day 天
    execute_time_hour: '08:00', //具体的时间点数例如08:00
    execute_time_local: '1', //1 触发规则后执行 2 触发规则前执行
    title: '', //标题
    content: '',
    media_content: [], //选则素材库
    retail_material: [], // 电商素材
    collect_form: [], // 收集表
    official_article: [], // 公众号图文
    local_link: [], //本地地址
    local_content: [], //本地媒体内容
    activity: [], //活动
    fileList: [],
    welcome_info: {}
});
const touch_type = reactive([
    { id: '1', name: '员工消息' },
    { id: '2', name: '短信' },
    { id: '3', name: '应用通知' },
    { id: '4', name: '公众号模版消息' },
    { id: '5', name: '抖音企业消息' },
    { id: '6', name: '小程序消息' }
]);
// 名字太长
const sortName = (val: string) => {
    if (IsNotEmpty(val) && val.length >= 30) {
        return val.substr(0, 10) + ' **** ' + val.substring(val.length - 8);
    }
    return val;
};
// 转化
const getDayStr = (str: string) => {
    const params = {
        day: '天',
        hour: '小时',
        minute: '分钟'
    };
    return params[str];
};
// 发送类型转换
const getSendType = (str: any) => {
    let text = '';
    switch (+str) {
        case 1:
            text = '发送员工消息';
            break;
        case 2:
            text = '员工私信任务';
            break;
        case 3:
            text = '应用通知员工';
            break;
        case 4:
            text = '发送公众号模版消息';
            break;
        case 5:
            text = '发送抖音企业消息';
            break;
        case 6:
            text = '发送小程序消息';
            break;
    }
    return text;
};
const getState = () => {
    stageList({
        page: 1,
        page_size: 100
    }).then((res: any) => {
        const arr = [];
        arr.push({ id: '0', name: '请选择客户阶段' });
        res.map((item: any) => (item.id = item.id + ''));
        state_list.value = [...arr, ...res];
    });
};
getState();
const getHolidDays = async () => {
    const res = await festivalDay();
    holiday_list.value = res;
};
getHolidDays();
const phase = () => {
    const { type, cust_stage } = props.formData.trigger_range.trigger_condition;
    const { stage_id } = props.formData.trigger_range.cust_stage;
    const {
        wake_object,
        birth_cycle,
        festival_cycle,
        sop_scene,
        festival_cycle_info: { festival_date, festival_name },
        trigger_condition: { tag_type }
    } = props.formData.trigger_range;
    const { time_type } = props.formData.trigger_range.msg_reply;
    const { time } = props.formData.trigger_range.cust_stage;
    const obj1 = state_list.value.filter((item: any) => item.id == +stage_id);
    const obj2 = state_list.value.filter((item: any) => item.id == +cust_stage);
    // props.formData.trigger_range.sop_scene
    let text = '';
    switch (+sop_scene) {
        case 1:
            if (wake_object == 1) {
                text = `【${obj1[0].name}】客户，${time}天未添加跟进记录`;
            } else {
                text = `客户${time}${getDayStr(time_type)}未回复企微员工消息`;
            }
            break;
        case 2:
            if (type == 1) {
                text = '客户【添加企微员工】';
            } else if (type == 2) {
                text = '客户【成为新客户】';
            }
            break;
        case 3:
            text = `客户进入【${obj2[0].name}】`;
            break;
        case 4:
            text = `生日在【${birth_cycle[0]}~${birth_cycle[1]}】的客户生日`;
            break;
        case 5:
            if (festival_cycle == 1) {
                const dateName = holiday_list.value.filter((item: any) => item.date == festival_date);
                text = `【${dateName[0]?.festival_name || festival_name}】`;
            } else {
                text = `【${festival_name}】`;
            }
            break;
        case 6:
            text = `客户【${tag_type == '1' ? '满足任意标签' : '满足所有标签'}】`;
            break;
    }
    return text;
};
const getSop = (res: any) => {
    if (rules.value.length >= 10) {
        ElMessage.warning('推送设置最多设置能10条！');
        return;
    }
    // 复制
    if (configStr.value == 'copy') {
        if (IsNotEmpty(res.id)) delete res.id; //编辑/复制 删除复制id
        rules.value.splice(configIndex.value + 1, 0, res);
        return;
    }
    // 编辑
    if (configStr.value == 'edit') {
        rules.value[configIndex.value] = res;
        return;
    }
    // 新增
    if (!IsNotEmpty(configStr.value)) {
        rules.value.push(res);
    }
};

const getFileList = (val: any) => {
    const { fileList, ruleIndex } = val;
    materialContentDataList.value[ruleIndex] = fileList;
};

const formatMaterialParams3 = (state: any) => {
    const { content: welcome_text, material } = state;
    let welcome_info = {};
    const welcome_material: any[] = [];
    const welcome_local_upload: any[] = [];
    const welcome_local_link: any[] = [];
    if (material.length) {
        material.forEach((item: any) => {
            const { type, id: media_content_id, local: local = false, code: code = '' } = item;
            const { link_title, link_url, link_decs, link_share_image } = item;
            if (local) {
                switch (Number(type)) {
                    case 3:
                        welcome_local_link.push({ link_title, link_url, link_decs, link_share_image });
                        break;
                    default:
                        welcome_local_upload.push({ type, code });
                        break;
                }
            } else {
                welcome_material.push({ type, media_content_id });
            }
        });
    }
    welcome_info = { welcome_text, welcome_material, welcome_local_upload, welcome_local_link };
    return { welcome_info };
};

// 打开配置项
const openCofig = (item?: any, key?: number, str?: string) => {
    configStr.value = str;
    configIndex.value = key; // 编辑
    if (IsNotEmpty(configStr.value)) {
        ruleIndex.value = key;
        SopConfigRef.value.formData.execute_time2 = item.execute_time;
        SopConfigRef.value.formData.execute_time_hour1 = item.execute_time_hour;
        SopConfigRef.value.materialContentData = materialContentDataList.value[key as number];
        SopConfigRef.value.getLook(item);
    } else {
        ruleIndex.value = materialContentDataList.value.length;
        delete SopConfigRef.value.formData.id;
        SopConfigRef.value.materialContentData = [];
        Object.assign(SopConfigRef.value.formData, formData.value);
    }
    SopConfigRef.value.appDialog.visible = true;
    SopConfigRef.value.appDialog.title = `【${props.formData.name}】添加推送规则`;
};
// 删除
const removeConfig = (item: any, index: number | string) => {
    ZWDeletdialogRef.value.appDialog.visible = true;
    ZWDeletdialogRef.value.content = `确定要删除“${item.title}”吗`;
    configIndex.value = index;
};
const confirmDel = () => {
    rules.value.splice(configIndex.value, 1);
    materialContentDataList.value.splice(configIndex.value, 1);
};

const init = () => {
    if (materialContentDataList.value.length) {
        materialContentFormList.value = materialContentDataList.value.map((item, index) => {
            const state = { material: item, content: props.formData.rule[index].welcome_info.welcome_text };
            return formatMaterialParams3(state);
        });
        rules.value.forEach((item, index) => {
            item.welcome_info = materialContentFormList.value[index]?.welcome_info;
        });
    }
};

let flag = false;

watch(
    () => props.formData,
    val => {
        if (props.pageType && val.rule.length && !flag) {
            materialContentDataList.value = props.formData.rule.map((item: any) =>
                initMaterialData(item.welcome_info.welcome_material)
            );
            init();
            flag = true;
        }
    },
    { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.step {
    .con_title {
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #eaeaea;
        padding-bottom: 20px;
        align-items: center;

        .main_title {
            font-size: 16px;
            font-family: PingFangSC-Medium, 'PingFang SC';
            font-weight: 500;
            color: #33302d;
        }

        .sub_title {
            margin-left: 14px;
            font-size: 12px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: #696969;
        }
    }

    .emty_content {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        height: 500px;

        .emty_img {
            margin-bottom: 40px;
        }

        .emty_title {
            font-size: 15px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: #969696;
        }
    }

    .main_rule {
        margin-top: 35px;
        min-height: 300px;
        border-left: 1px dashed #ffc69e;
        padding-left: 20px;

        .rule_item {
            width: 1000px;
            margin-bottom: 35px;
        }

        .rule_item_title {
            margin-bottom: 13px;

            .index_num {
                float: left;
                margin-left: -30px;
                width: 18px;
                height: 18px;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #fff;
                border-radius: 50%;
                border: 1px solid #ff6b00;
                font-size: 12px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                color: #ff6b00;
            }

            .title_icon {
                width: 17px;
                height: 17px;
                display: inline-block;
                background: #ff9800;
                margin-right: 5px;
                border-radius: 2px;
                text-align: center;
                font-size: 12px;
                line-height: 17px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                color: #fff;
            }

            .week_icon {
                border-radius: 50%;
                background: rgb(24 144 255);
            }

            span {
                font-size: 14px;
                font-family: PingFangSC-Regular, 'PingFang SC';
                font-weight: 400;
                color: #262626;
                line-height: 20px;
            }
        }

        .rule_box {
            background: #fff;

            // box-shadow: 0px 4px 4px 0px rgba(240, 240, 240, 0.5);
            border: 1px solid #eaeaea;
            padding: 20px;

            .rule_tit {
                font-size: 14px;
                font-family: PingFangSC-Medium, 'PingFang SC';
                font-weight: 500;
                color: #262626;
                line-height: 20px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 16px;
            }

            .rule_content {
                background: #f8f8f8;
                padding: 15px 20px;
                font-size: 14px;
                font-family: PingFangSC-Regular, 'PingFang SC';
                font-weight: 400;
                color: #262626;
                line-height: 20px;
            }

            .rule_file {
                margin-top: 20px;

                .file_item {
                    width: 440px;
                    height: 32px;
                    background: #f8f8f8;
                    box-sizing: border-box;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 0 14px;
                    margin-bottom: 2px;

                    div {
                        display: flex;
                        align-items: center;

                        span {
                            display: inline-block;
                            width: 380px;
                            overflow: hidden;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            font-size: 14px;
                            line-height: 20px;
                            font-family: STHeitiSC-Light, STHeitiSC;
                            font-weight: 300;
                            color: #33302d;
                        }
                    }

                    .file_icon {
                        width: 20px;
                        height: 20px;
                        margin-right: 7px;
                    }
                }
            }
        }
    }
}
</style>
